<template>
<a-modal v-model:open="open" :title="title" @ok="onSubmit" :confirmLoading="loading">
  <a-form :model="form" ref="formRef" :rules="rules" :label-col="formCol.labelCol" :wrapper-col="formCol.wrapperCol">
    <a-form-item label="分类名称" name="name">
      <a-input v-model:value="form.name" show-count :maxlength="20" name="name" placeholder="请输入分类名称" />
    </a-form-item>
    <a-form-item label="父级分类" name="pid">
      <a-tree-select v-model:value="form.pid" 
          placeholder="请选择父级分类" 
          name="pid" 
          :treeData="categoryList"
          allow-clear
          tree-default-expand-all
          show-search
          :field-names="{ label: 'name', value: 'id'}"
          tree-node-filter-prop="name"/>
    </a-form-item>
    <a-form-item label="状态" name="status">
      <a-radio-group v-model:value="form.status" name="status">
        <a-radio :value="1">启用</a-radio>
        <a-radio :value="0">禁用</a-radio>
      </a-radio-group>
    </a-form-item>
  </a-form>
</a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { formCol } from '@/config';
import type { FormInstance } from 'ant-design-vue';
import useMessage from '@/hooks/useMessage';
import { updateCategory, createCategory } from '@/server/modules/category';
import { hasPermission } from '@/hooks';

const open = defineModel('open')
const emits = defineEmits(['ok'])
const {dataItem,pid} = defineProps<{dataItem?:Category,pid?:number}>()
const categoryList = ref<Category[]>([])

const title = computed(() => {
  return dataItem ? '编辑分类' : '新增分类'
})
const loading = ref(false)
const formRef = ref<FormInstance>()
const form = reactive<CategoryForm>({
  id: 0,
  name: '',
  pid: 0,
  status:1 
})
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}
const getCategories = ()=>{
  const cache = JSON.parse(localStorage.getItem('categoryList') || '[]')
  categoryList.value = [{id:0,name:'一级分类'},...cache]
}
//监听传递数值 赋值给form 判断更新还是删除
watch(()=>dataItem,(value)=>{
  if(value?.id){
    Object.assign(form,value)
  }else{
    Object.assign(form,{
      id:0,
      name:'',
      pid:0,
      status:1
    })
  }
  getCategories()
},{ immediate: true })
//监听是否传递pid子分类
watch(()=>pid,async ()=>{ form.pid = pid},{immediate: true})
const onSubmit = async () => {
  if(!hasPermission('create') && !hasPermission('update')) return
  try { 
    loading.value = true
    await formRef.value?.validate()
    const res = await (dataItem?.id ? updateCategory(form.id as number,form) : createCategory(form))
    if(res.code === 200){
      emits('ok')
      useMessage(res.code,res.message)
      open.value = false
    }else{
      useMessage(res.code,res.message)
    }
  } catch{
    return useMessage(403,'请填写正确的信息')
  } finally{
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
}
</script>

<style scoped>
/* 样式 */
</style>